var module = require('./lib/module.Base');
$(document).ready(function($) {
    var HTML_template = {
        shippingList:'<div class="buttons-tab dbuttons-tab2" id="shippingList">' +
                        '<a href="#tabN" class="tab-link active button">待送货（<%=_.toLength(_.uniqBy(_.result(_.groupBy(data,\'orderStatus\'),\'N\'),\'storeName\'))）</a>' +
                        '<a href="#tabY" class="tab-link button">已送货（<%=_.uniqBy(_.result(_.groupBy(data,\'orderStatus\'),\'Y\'),\'storeName\').length%>）</a></div>' +
                        '<div class="content-block margin0 padding0"><div class="tabs">' +
                        '<% _.forEach({N:_.groupBy(data,\'orderStatus\')[\'N\'],Y:_.groupBy(data,\'orderStatus\')[\'Y\']}, function(shipping,shippingType) { %>' +
                        '<div id="tab<%=shippingType%>" class="tab <%if(_.eq(shippingType,\'N\')){%>active<%}%>">' +
                        '<div class="content-padded"><p class="margin0 c6 fs75"><span><%if(_.eq(shippingType,\'N\')){%>提货<%}else{%>已发货<%}%>：</span><% _.forEach(_.groupBy(shipping,\'carrierName\'), function(item,key) { %><span><%=key%>（<%=_.sumBy(item,\'quantity\')%>箱）</span><%})%></p></div>' +
                        '<% _.forEach(_.groupBy(shipping,\'storeName\'), function(list,storeName) { %>' +
                        '<div class="order-box bgf mb5h"><div class="content-padded"><div class="row no-gutter pt5h pb5h borderB"><div class="col-40 c9"><p class="margin0 c3 fs75"><%=_.last(list).storeName%></p></div><div class="col-60 c6 tar"><p class="margin0 fs75"><%=_.last(list).address%></p></div></div><div class="row no-gutter pt5h pb5h"><div class="col-75 c9"><p class="margin0 c6 fs75"><% _.forEach(_.groupBy(_.orderBy(list,[\'carrierName\',\'id\'],[\'desc\',\'asc\']),\'carrierName\'), function(orderItem,itemName) {%><span class="mr5h"><%=itemName%> <strong class="blue"><%=_.sumBy(orderItem,\'quantity\')%></strong> 箱</span><%})%></p></div><div class="col-10">&nbsp;</div><div class="col-15 c6 tar"><%if(shippingType == \'N\'){%><a href="javascript:void(0);" data-send-id="<%= _.join(_.toArray(_.mapValues(list,\'id\'))) %>" class="button button-fill red-btn send-button">配送</a><%}else{%><p class="margin0 c9 tar fs75">已送货</p><%}%></div></div></div></div>' +
                        '<%})%>' +
                        '</div><%})%></div></div>',
        inputTemp:'<% _.forEach(data, function(item,key) { %><div class="content-padded fs75 "><div class="row no-gutter"><div class="col-45" style="width: 45%; overflow: hidden;"><%=item.carrierName%></div><div class="col-20"><p class="margin0 tar c6">重量:</p></div><div class="col-25"><p class="margin0 tac c3"><input type="text" class="c3 bgn wall quantity-input" value="<%=item.quantity%>" name="<%=item.id%>"></p></div><div class="col-10">kg</div></div></div><%})%>',
        success:'<p class="margin0 c9 tar fs75">已送货</p>'
    };

    var localData = {
        shippingList:[]
    };
    _.extend(module.PageEventBase.prototype,{
        delivery:function ($page,pageId,result) {
            if(result.status){
                localData.shippingList = result.data.list;
            }
            $.loadTemplate($page, {
                shippingList:{data:localData.shippingList}
            },HTML_template).then(function(){
                var modalItems = [];
                $page.find('.send-button').on('click',function () {
                    var btnDom = $(this);
                    var ids = _.split($(this).data('sendId'),',').map(_.toInteger);
                    var modalItems = _.filter(localData.shippingList,function (o) {
                        return _.indexOf(ids,o.id) >= 0;
                    });
                    var templateModal = _.template(HTML_template.inputTemp);
                    $.modal({
                        title:  '请输入商品重量:',
                        text: templateModal({data:modalItems}),
                        buttons: [
                            {
                                text: '取消',
                                onClick: function() {

                                }
                            },
                            {
                                text: '确认',
                                onClick: function(e) {
                                    var changeData = _.chain($(e).find('input')).map(function (input) {
                                            return {
                                                id:_.toInteger($(input).attr('name')),
                                                quantity:_.floor($(input).val(),2),
                                                isError:/^\d+(\.\d+)?$/.test($(input).val())
                                            }
                                    }).value();
                                    if(_.filter(changeData,{isError:false}).length > 0){
                                        $.alert('请输入正确的产品重量');
                                    }else{
                                        modalItems = modalItems.map(function (item) {
                                            return _.findIndex(changeData,{id:item.id}) >= 0 ? _.assign(item,_.find(changeData,{id:item.id})) : item;
                                        });
                                        //提交事件
                                        $.alert('发货成功',function () {
                                            btnDom.parent().append(HTML_template.success);
                                            btnDom.remove();
                                        });
                                    }

                                }
                            }
                        ]
                    });

                });
            });
        }
    });
    var EventList = new module.PageEventBase();
    EventList.setResolve({
        delivery:{status:true,url:'/app/shippingOrders.htm',params:{}},
    });
    var pageId = $('.page.page-current').attr('id');
    EventList.init($('.page.page-current'),pageId);
});